import logging

from db import model
from google.appengine.ext import db
from student_client import StudentClient
from survey_client import SurveyClient


ACTIVE_DORMS = [
  'Loughran Hall',
  'Madonna Hall',
  'Regina Hall'
]


class ProgressStats(object):
  def __init__(self, status):
    self.status = status
    self.student_count = 0

  def addStudent(self, student):
    self.student_count += 1


class RaStats(object):
  def __init__(self, ra_name):
    self.ra_name = ra_name
    self.student_count = 0
    self.completed_count = 0
    self.percent_completed = 0

  def addStudent(self, student):
    self.student_count += 1
    if student.status:
      self.completed_count += 1
    self.percent_completed = \
        int((float(self.completed_count) / float(self.student_count)) * 100)


class DormStats(object):
  def __init__(self, dorm_name):
    self.dorm_name = dorm_name
    self.student_count = 0
    self.completed_count = 0
    self.percent_completed = 0

  def addStudent(self, student):
    self.student_count += 1
    if student.status:
      self.completed_count += 1
    self.percent_completed = \
        int((float(self.completed_count) / float(self.student_count)) * 100)


class StatsClient(object):
  def __init__(self):
    self.student_client = StudentClient()
    self.survey_client = SurveyClient()

  def getStudentMap(self, session=model.CURRENT_SESSION):
    students = self.student_client.getStudents(session=session)

    student_map = {}
    for student in students:
      if student.dorm in ACTIVE_DORMS:
        student_map[student.key().id()] = student
    return student_map

  def getFriendSurveyMap(self):
    friend_surveys = self.survey_client.getFriendSurveys(
        session=model.CURRENT_SESSION)
    friend_survey_map = {}
    for friend_survey in friend_surveys:
      if friend_survey.student_id in friend_survey_map:
        friend_survey_map[friend_survey.student_id].append(
            friend_survey.friend.key().id())
      else:
        friend_survey_map[friend_survey.student_id] = \
            [friend_survey.friend.key().id()]
    return friend_survey_map

  def getStudentsProgress(self, student_map):
    stats_map = {}

    total_taken_stats = ProgressStats('Total Taken')

    for student in student_map.values():
      if not student.status:
        continue

      if student.status in stats_map:
        progress_stats = stats_map[student.status]
        progress_stats.addStudent(student)
      else:
        progress_stats = ProgressStats(student.status)
        progress_stats.addStudent(student)
        stats_map[student.status] = progress_stats

      total_taken_stats.addStudent(student)

    stats = stats_map.values()
    stats.append(total_taken_stats)
    return stats

  def getStudentsByRa(self, student_map):
    stats_map = {}
    for student in student_map.values():
      if student.ra in stats_map:
        ra_stats = stats_map[student.ra]
        ra_stats.addStudent(student)
      else:
        ra_stats = RaStats(student.ra)
        ra_stats.addStudent(student)
        stats_map[student.ra] = ra_stats
  
    return stats_map.values()

  def getStudentsByDorm(self, student_map):
    stats_map = {}
    for student in student_map.values():
      if student.dorm in stats_map:
        dorm_stats = stats_map[student.dorm]
        dorm_stats.addStudent(student)
      else:
        dorm_stats = DormStats(student.dorm)
        dorm_stats.addStudent(student)
        stats_map[student.dorm] = dorm_stats
  
    return stats_map.values()

  def getFriendSurveyStats(self, student_map):
    # TODO(ncabrera): GET THIS TO WORK!
    return {}

    friend_survey_map = self.getFriendSurveyMap()

    stats_map = {}
    unique_friends = {}
    for student_id, friend_ids in friend_survey_map.iteritems():
      for friend_id in friend_ids:
        unique_friends[friend_id] = True
        if student_id in stats_map:
          stats_map[student_id] += 1
        else:
          stats_map[student_id] = 1

    student_stats = []
    min_friends = 10000
    max_friends = 0
    total_friends = 0
    for student_id, friend_count in stats_map.iteritems():
      total_friends += friend_count
      if min_friends > friend_count:
        min_friends = friend_count
      if max_friends < friend_count:
        max_friends = friend_count

      if student_id in student_map:
        fb_friend_count = student_map[student_id].fb_friend_count
        fb_match_count = student_map[student_id].fb_match_count
      else:
        fb_friend_count = 0
        fb_match_count = 0
        
      student_stats.append({
        'student_id': student_id,
        'friend_count': friend_count,
        'fb_friends': fb_friend_count,
        'fb_matches': fb_match_count
      })

    return {
      'unique_friends': len(unique_friends.keys()),
      'avg_friends': int(total_friends / len(student_stats)),
      'max_friends': max_friends,
      'min_friends': min_friends,
      'student_stats': student_stats
    }
